import 'dart:convert';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:esp_blufi/esp_blufi.dart';

import 'blu_been.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _espBlufiPlugin = EspBlufi();
  List<BluBeen> scanResult = <BluBeen>[];

  @override
  void initState() {
    super.initState();
    _onMessageReceived();
    _scanDeviceInfo();
  }

  ///接收蓝牙数据
  void _onMessageReceived() {
    EspBlufi.instance.onMessageReceived(
        successCallback: (data) {
          Map<String, dynamic> mapData = json.decode(data!);
          _handleMessage(mapData);
        },
        errorCallback: (error) {});
  }

  ///蓝牙扫描设备
  Future<void> _scanDeviceInfo() async {
    await EspBlufi.instance.scanDeviceInfo(filterString: 'XB-262');
    await EspBlufi.instance.getAllPairedDevice( );
  }

  void _handleMessage(Map<String, dynamic> mapData) {
    if (!mapData.containsKey('key')) return;
    String key = mapData['key'];
    if (key != "ble_scan_result") {
      print(mapData);
    }

    switch (key) {
      case "each_connected_device":
        print("已经连接的设备-----》");
        break;
      case 'ble_scan_result':
        Map<String, dynamic> peripheral = mapData['value'];

        String address = peripheral['address'];
        String name = peripheral['name'];
        String rssi = peripheral['rssi'];
        BluBeen bluBeen = BluBeen(address: address, name: name, rssi: rssi);
        if (!scanResult.contains(bluBeen)) {
          scanResult.add(bluBeen);
          setState(() {});
        }
        break;
      case 'GATT_SUCCESS':
        break;
      case 'peripheral_connect':
        break;
      case 'discover_service':
      case 'request_mtu':
      case 'device_status':
        // logger.d(mapData);
        break;
      case 'device_wifi_connect':
        break;
      case 'wifi_info':
        Map<String, dynamic> value = mapData['value'];
        String ssid = value['ssid'];

        break;
      case 'receive_device_custom_data':
      case "configure_params": //{key: configure_params, value: 1,  address: CFABEB8D-D88F-7014-4698-0CDBF6 9E4005}
        break;
      default:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Bluetooth Devices'),
        ),
        body: ListView.builder(
          itemCount: scanResult.length,
          itemBuilder: (context, index) {
            BluBeen device = scanResult[index];
            return ListTile(
              title: Text(device.name ?? 'Unknown Device'),
              subtitle: Text('RSSI: ${device.rssi}'),
              trailing: Text(device.address ?? 'No Address'),
              onTap: () {
                // 可以在这里添加连接逻辑
                print('Connecting to ${device.name}');
                connectPeripheral(device);
              },
            );
          },
        ),
      ),
    );
  }

  void connectPeripheral(BluBeen device) async {
    await EspBlufi.instance
        .connectPeripheral(peripheralAddress: device.address);
  }
}
